﻿using System;
using System.Net;
using AbstraX.Contracts;
using System.Collections.Generic;
using AbstraX.Bindings;
using System.Linq;
using AbstraX.BindingsTreeEntities;

namespace DataBindings
{
    public class DataBindingsDaemon : IBuildUIDaemon
    {
        private IDomainHostApplication host;
        private List<IBindingsTree> bindingsTrees;
        public string TreeIDs { get; set; }

        public DataBindingsDaemon(IDomainHostApplication host)
        {
            this.host = host;
        }

        public bool MoveNext(string lastUIComponentURL)
        {
            return false;
        }

        public string GetProperty(string UIComponentURL, string propertyName)
        {
            var propertyValue = (string) this.GetType().GetProperty(propertyName).GetValue(this, null);

            return propertyValue;
        }

        public void SetProperty(string UIComponentURL, string propertyName, string value)
        {
            this.GetType().GetProperty(propertyName).SetValue(this, value, null);
        }

        public void Finish(string lastUIComponentURL)
        {
        }

        public List<IBindingsTree> BindingsTrees
        {
            get
            {
                if (bindingsTrees == null)
                {
                    var treeIDs = this.TreeIDs.Split(',');

                    bindingsTrees = new List<IBindingsTree>();

                    foreach (var treeID in treeIDs)
                    {
                        var tree = host.BindingsTreeCache.CachedTrees.Values.Single(t => t.CachedNodes.Nodes.ContainsKey(treeID));
                        var bindingsTree = tree.CachedNodes.Nodes[treeID];

                        bindingsTrees.Add(tree.CachedNodes.BindingsTree);
                    }
                }

                return bindingsTrees;
            }
        }
    }
}
